package com.itservice.uzalarm;


import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Point;
import android.view.Display;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.WindowManager;

public class MazeProc extends SurfaceView implements SurfaceHolder.Callback,Runnable
{
	public static final int MAZE_SCREENSIZE = 23;
	public static int MAZE_X_OFFSET = 0;
	public static int MAZE_Y_OFFSET = 0;

	private int dwWall[][];

	private MazeGraphics		mGraphics;		// グラフィック
    private SurfaceHolder	holder;			// サーフェイスホルダー
    private Thread			mMazeThread;	// 描画スレッド

    // 描画bitmap達
    private Bitmap bmpChara1	= null;	// キャラクタ1
    private Bitmap bmpChara2	= null;	// キャラクタ2
    private Bitmap bmpGround	= null;	// 地面(進行可能エリア)
    private Bitmap bmpWall		= null;	// 壁(進行不可エリア)

    private Bitmap bmpstop1	= null;
    private Bitmap bmpstop2	= null;
    private Bitmap bmpstop3	= null;

    private Bitmap bmpGIcon1	= null;
    private Bitmap bmpGIcon2	= null;
    private Bitmap bmpGIcon3	= null;

    private int dwMazeRoadSize	= 0;	// 1画像の描画サイズ
    private int dwDisWidth		= 0;	// スクリーン 横サイズ
    private int dwDisHeight	= 0;	// スクリーン 縦サイズ
    
    private static int x;				// 現在地 x
    private static int y;				// 現在地 y
    private static int OLD_x;			// 比較用：元座標x
    private static int OLD_y;			// 比較用：元座標y
    private static int NEW_x;			// 比較用：移動先座標x
    private static int NEW_y;			// 比較用：移動先座標y
    private static int Goal_x = 0;	// Goal座標
    private static int Goal_y = 0;	// Goal座標

    private static boolean state = false;

	public int	dwMove	= 0;	// 描画キャラ切り替え用
	public Context mContext;
	
	public MazeProc(Context context, SurfaceView sv)
	{
		super(context);
		Resources res = this.getResources();
		mContext = context;

		WindowManager wm	= (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
		Display display		= wm.getDefaultDisplay();

		state = false;

		// //SurfaceViewからholderを取得し、インターフェイスを設定する。
		holder = sv.getHolder();
	
		// サイズの取得
		dwDisWidth	= display.getWidth();
		dwDisHeight	= display.getHeight();

		if(this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
		{
			dwMazeRoadSize = dwDisHeight / MAZE_SCREENSIZE + 1;
			MAZE_X_OFFSET = 100;
    		x	= dwMazeRoadSize;
    		y	= dwMazeRoadSize;
        }
        else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
        {
    		dwMazeRoadSize = dwDisWidth / MAZE_SCREENSIZE + 1;
    		MAZE_Y_OFFSET = 150;
    		x	= dwMazeRoadSize;
    		y	= dwMazeRoadSize;
    	}

		//グラフィックスの生成
		holder.addCallback(this);
        mGraphics = new MazeGraphics(holder);

        // 歩行キャラクタのリソース指定
		bmpChara1 = BitmapFactory.decodeResource(res, R.drawable.chara1);
		bmpChara1 = bmpResize(dwMazeRoadSize,dwMazeRoadSize,bmpChara1);

		bmpChara2 = BitmapFactory.decodeResource(res, R.drawable.chara2);
		bmpChara2 = bmpResize(dwMazeRoadSize,dwMazeRoadSize,bmpChara2);

		// フィールド用リソース
		bmpGround = BitmapFactory.decodeResource(res, R.drawable.ground);
		bmpGround = bmpResize(dwMazeRoadSize,dwMazeRoadSize, bmpGround);

		// 壁リソース
		bmpWall	  = BitmapFactory.decodeResource(res, R.drawable.wall);
		bmpWall   = bmpResize(dwMazeRoadSize,dwMazeRoadSize,bmpWall);

		// STOPボタン
		bmpstop1 = BitmapFactory.decodeResource(res, R.drawable.stop1);
		bmpstop1 = bmpResize(120,40,bmpstop1);
		bmpstop2 = BitmapFactory.decodeResource(res, R.drawable.stop2);
		bmpstop2 = bmpResize(120,40,bmpstop2);
		bmpstop3 = BitmapFactory.decodeResource(res, R.drawable.stop3);
		bmpstop3 = bmpResize(120,40,bmpstop3);

		// ドロイドちゃん
		bmpGIcon1 = BitmapFactory.decodeResource(res, R.drawable.droidchan1);
		bmpGIcon1 = bmpResize(120,40,bmpGIcon1);
		bmpGIcon2 = BitmapFactory.decodeResource(res, R.drawable.droidchanwin1);
		bmpGIcon2 = bmpResize(120,40,bmpGIcon2);
		bmpGIcon3 = BitmapFactory.decodeResource(res, R.drawable.droidchanwin2);
		bmpGIcon3 = bmpResize(120,40,bmpGIcon3);
		
		// タッチ判定用
		OLD_x	= dwMazeRoadSize;
		OLD_y	= dwMazeRoadSize;
		NEW_x	= dwMazeRoadSize;
		NEW_y	= dwMazeRoadSize;

		// 迷路情報配列
		dwWall = new int[MAZE_SCREENSIZE + 2][MAZE_SCREENSIZE + 2];

		// 迷路作成
		createMaze();

	}

	//------------------------------------------------
	// 道サイズに合わせてbitmapリサイズ
	//------------------------------------------------
	public Bitmap bmpResize(float resizeWidth, float resizeHeight, Bitmap bitmap)
	{
		float resizeScaleWidth;
		float resizeScaleHeight;

		Matrix matrix = new Matrix();
		resizeScaleWidth = resizeWidth / bitmap.getWidth();
		resizeScaleHeight = resizeHeight / bitmap.getHeight() ;
		matrix.postScale(resizeScaleWidth, resizeScaleHeight);
		Bitmap resizeBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
		return resizeBitmap;
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int w, int h)
	{
		// NOP
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) 
	{
		mMazeThread = new Thread(this);
		mMazeThread.start();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) 
	{
		mMazeThread = null;
	}

	//-----------------------------------------------------
	// 描画処理スレッド
	//-----------------------------------------------------
	@Override
	public void run()
	{
		int i = 0;
		int j = 0;


		while( null != mMazeThread)
        {
			try
			{
				// CPU占有回避
				Thread.sleep(30);
			}
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}

			// キャンバスのロック
			mGraphics.lock();

			// 背景色セット
			mGraphics.setCanvasColor(Color.BLACK);

			// paint用カラーセット
			mGraphics.setColor(Color.WHITE);

			// 時刻表示更新
			mGraphics.DrawTime();

			// 停止ボタン
			if(state)
			{
				mGraphics.drawBitmap(bmpstop2, 320, 100);
			}
			else
			{
				mGraphics.drawBitmap(bmpstop1, 320, 100);
			}

			// 迷路描画
			for (i = 0 ; i < MAZE_SCREENSIZE ; i++)
			{
				for (j = 0 ; j < MAZE_SCREENSIZE ; j++)
				{
					if (dwWall[i][j] == 1)
					{
						mGraphics.drawBitmap(bmpWall, j * dwMazeRoadSize + MAZE_X_OFFSET, i * dwMazeRoadSize + MAZE_Y_OFFSET);
					}
					else
					{
						mGraphics.drawBitmap(bmpGround, j * dwMazeRoadSize + MAZE_X_OFFSET, i * dwMazeRoadSize + MAZE_Y_OFFSET);
					}
				}
			}

			// Goalの設定
			mGraphics.drawBitmap(bmpGround, (j-2) * dwMazeRoadSize + MAZE_X_OFFSET, (i-1) * dwMazeRoadSize + MAZE_Y_OFFSET);
			Goal_y = (i-1)*dwMazeRoadSize;
			Goal_x = (j-2)*dwMazeRoadSize;
			dwWall[i-2][j-2] = 0;
			dwWall[i-1][j-2] = 0;
			mGraphics.drawString("Goal!", (j-3) * dwMazeRoadSize, (i-1) * dwMazeRoadSize + MAZE_Y_OFFSET + 45, 20);

			// キャラの描画
			if(dwMove %2 == 0)
			{
				mGraphics.drawBitmap(bmpChara1, x, y + MAZE_Y_OFFSET);
			}
			else
			{
				mGraphics.drawBitmap(bmpChara2, x, y + MAZE_Y_OFFSET);
			}
			dwMove++;
			mGraphics.unlock();
       }
	}


	//------------------------------------------------------
	// createMaze()
	// 迷路作成
	//------------------------------------------------------
	private void createMaze()
	{
		int dx[] = {0, 1, 0, -1};
		int dy[] = {1, 0, -1, 0};

		int i = 0;
		int j = 0;
		// 配列初期化
		for (i = 0 ; i < MAZE_SCREENSIZE ; i++)
		{
			for (j = 0 ; j < MAZE_SCREENSIZE ; j++)
			{
				dwWall[i][j] = 0;
			}
		}

		// 枠の作成
		for (i = 0 ; i < MAZE_SCREENSIZE ; i++)
		{
			dwWall[0][i]					= 1;
			dwWall[MAZE_SCREENSIZE-1][i]	= 1;
			dwWall[i][0]					= 1;
			dwWall[i][MAZE_SCREENSIZE-1]	= 1;
		}
		for (i = 1 ; i <= MAZE_SCREENSIZE/2-1 ; i++)
		{
			for (j = 1 ; j <= MAZE_SCREENSIZE/2-1 ; j++)
			{
				dwWall[i * 2][j * 2] = 1;
			}
		}

		// 乱数から道の作成
		for (i = 1 ; i <= MAZE_SCREENSIZE/2-1 ; i++)
		{
			for (j = 1 ; j <= MAZE_SCREENSIZE/2-1 ; j++)
			{
				if (i == 1)
				{
					int rand = (int)(Math.random() * 4);
					dwWall[i * 2 + dx[rand]][j * 2 + dy[rand]] = 1;
				}
				else
				{
					boolean flag = true;
					while(flag)
					{
						int rand = (int)(Math.random() * 3);
						if (dwWall[i * 2 + dx[rand]][j * 2 + dy[rand]] == 0)
						{
							dwWall[i * 2 + dx[rand]][j * 2 + dy[rand]] = 1;
							flag = false;
						}
					}
				}
			}
		}
	}

	//-----------------------------------------------------
	// Keyディスパッチ処理
	//-----------------------------------------------------
	@Override
	public boolean dispatchKeyEvent(KeyEvent event)
    {
        if (event.getAction()==KeyEvent.ACTION_DOWN)
        {
            switch (event.getKeyCode())
            {
            	// Backキー無効
                case KeyEvent.KEYCODE_BACK:
                    return true;
            }
        }
        return super.dispatchKeyEvent(event);
    }

	//----------------------------------
	// タッチイベント時の処理
	// → キャラの進行、壁判定
	//----------------------------------
	@Override
	public boolean onTouchEvent(MotionEvent event)
	{
        Point p = new Point();
        p.x = (int)event.getX();
        p.y = (int)event.getY();

		switch(event.getAction())
		{
		case MotionEvent.ACTION_DOWN:
			OLD_x = (int)event.getX();
			OLD_y = (int)event.getY();
			break;
		case MotionEvent.ACTION_UP:
			NEW_x = (int)event.getX();
			NEW_y = (int)event.getY();

			int xDiff = NEW_x - OLD_x;
			int yDiff = NEW_y - OLD_y;

			if(false == state)
			{
				// 縦方向 タッチ判定
				if( Math.abs(yDiff) > (dwMazeRoadSize/2 + 1) )
				{
					// プラス方向移動
					if(yDiff > 0)
					{
						// 道判定
						if(dwWall[y/dwMazeRoadSize + 1][x/dwMazeRoadSize] == 0)
						{
							y += dwMazeRoadSize;
						}
					}
					else
					{
						if(y >= (dwMazeRoadSize * 2))
						{
							// 道判定
							if(dwWall[y/dwMazeRoadSize - 1][x/dwMazeRoadSize] == 0)
							{
								y -= dwMazeRoadSize;
							}
						}
					}
				}
	
				// 横方向タッチ判定
				if( Math.abs(xDiff) > (dwMazeRoadSize/2 + 1) )
				{
					if(xDiff > 0)
					{
						// 道判定
						if(dwWall[y/dwMazeRoadSize][x/dwMazeRoadSize + 1] == 0)
						{
							x += dwMazeRoadSize;
						}
					}
					else
					{
						if(x >= (dwMazeRoadSize * 2))
						{
							// 道判定
							if(dwWall[y/dwMazeRoadSize][x/dwMazeRoadSize - 1] == 0)
							{
								x -= dwMazeRoadSize;
							}
						}
					}
				}

				if(x >= Goal_x && y >= Goal_y)
				{
					/*
					new AlertDialog.Builder(mContext)
					.setIcon(R.drawable.icon)
					.setMessage("GOAL!!!")
					.setPositiveButton("OK", new DialogInterface.OnClickListener()
					{
						public void onClick(DialogInterface dialog, int whichButton)
						{
							mMazeThread = null;
							meiro3.exit();
						}
					})
					.show();
					*/
					state = true;
				}
			}

			if((p.x >= 320 && p.x <= 440) && (p.y >= 150 && p.y <= 190) && true == state)
			{
				mGraphics.drawBitmap(bmpstop3, 320, 100);
				mMazeThread = null;

				/* Start Service */
				Intent sintent = new Intent(mContext, UzalarmService.class);
				mContext.startService(sintent);
				
				//Activityをとめる。
				return false;
			}
			break;
		}
		return true;
	}

}
